import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

void main() {
  runApp(
    // Adding ProviderScope enables Riverpod for the entire project
    const ProviderScope(child: MyApp()),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: UserListPage());
  }
}

class User {
  final int id;
  final String name;
  final String email;
  final String avatar;
  final String company;

  User({
    required this.id,
    required this.name,
    required this.email,
    required this.avatar,
    required this.company,
  });

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
      avatar: json['avatar'],
      company: json['company'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'email': email,
      'avatar': avatar,
      'company': company,
    };
  }
}

// 分页响应模型
class PaginatedResponse<T> {
  final List<T> data;
  final int page;
  final int totalPages;
  final int totalItems;
  final bool hasNext;

  PaginatedResponse({
    required this.data,
    required this.page,
    required this.totalPages,
    required this.totalItems,
    required this.hasNext,
  });
}

// API服务类
class ApiService {
  // 模拟网络延迟
  Future<void> _delay() async {
    await Future.delayed(Duration(milliseconds: 800 + Random().nextInt(1200)));
  }

  // 获取用户列表
  Future<PaginatedResponse<User>> getUsers(int page,
      {int pageSize = 10}) async {
    await _delay();

    // 模拟偶尔的网络错误
    if (Random().nextInt(10) == 0) {
      throw Exception('网络连接失败');
    }

    // 生成模拟数据
    final users = List.generate(pageSize, (index) {
      final globalIndex = (page - 1) * pageSize + index;
      return User(
        id: globalIndex,
        name: '用户 $globalIndex',
        email: 'user$globalIndex@example.com',
        avatar: 'https://picsum.photos/100/100?random=$globalIndex',
        company: '公司 ${globalIndex % 5}',
      );
    });

    const totalItems = 50;
    final totalPages = (totalItems / pageSize).ceil();

    return PaginatedResponse(
      data: users,
      page: page,
      totalPages: totalPages,
      totalItems: totalItems,
      hasNext: page < totalPages,
    );
  }

  // 获取单个用户详情
  Future<User> getUserDetails(int userId) async {
    await _delay();

    if (Random().nextInt(8) == 0) {
      throw Exception('用户不存在');
    }

    return User(
      id: userId,
      name: '用户详情 $userId',
      email: 'details$userId@example.com',
      avatar: 'https://picsum.photos/200/200?random=$userId',
      company: '详细公司 ${userId % 3}',
    );
  }
}

// API服务Provider
final apiServiceProvider = Provider<ApiService>((ref) => ApiService());

// 用户列表AsyncNotifier
class UserListNotifier extends AsyncNotifier<List<User>> {
  int _currentPage = 1;
  List<User> _allUsers = [];

  @override
  Future<List<User>> build() async {
    // 初始化时加载第一页
    return _loadPage(1, refresh: true);
  }

  // 刷新数据
  Future<void> refresh() async {
    state = const AsyncLoading();
    try {
      final users = await _loadPage(1, refresh: true);
      state = AsyncValue.data(users);
    } catch (error, stackTrace) {
      state = AsyncValue.error(error, stackTrace);
    }
  }

  // 加载更多数据
  Future<void> loadMore() async {
    if (state.hasError || state.isLoading) return;

    final currentUsers = state.value ?? [];
    state = AsyncValue.data(currentUsers); // 保持当前状态

    try {
      final newUsers = await _loadPage(_currentPage + 1);
      final allUsers = [...currentUsers, ...newUsers];
      state = AsyncValue.data(allUsers);
    } catch (error, stackTrace) {
      // 加载更多失败时，保持当前数据，只显示错误
      state = AsyncValue.error(error, stackTrace);
    }
  }

  // 私有方法：加载指定页面
  Future<List<User>> _loadPage(int page, {bool refresh = false}) async {
    final apiService = ref.read(apiServiceProvider);
    final response = await apiService.getUsers(page);

    if (refresh) {
      _currentPage = 1;
      _allUsers = response.data;
    } else {
      _currentPage = page;
      _allUsers.addAll(response.data);
    }

    return List.from(_allUsers);
  }

  // 检查是否还有更多数据
  bool get hasMore {
    return _currentPage < 5; // 假设总共5页
  }
}

// 用户列表Provider
final userListProvider = AsyncNotifierProvider<UserListNotifier, List<User>>(
  () => UserListNotifier(),
);

// 单个用户详情Provider
final userDetailsProvider =
    FutureProvider.family<User, int>((ref, userId) async {
  final apiService = ref.read(apiServiceProvider);
  return apiService.getUserDetails(userId);
});

// 用户搜索Provider
final userSearchProvider =
    FutureProvider.family<List<User>, String>((ref, query) async {
  if (query.isEmpty) return [];

  // 从用户列表中搜索
  final users = await ref.watch(userListProvider.future);
  return users
      .where((user) =>
          user.name.toLowerCase().contains(query.toLowerCase()) ||
          user.email.toLowerCase().contains(query.toLowerCase()))
      .toList();
});

class UserListPage extends ConsumerStatefulWidget {
  @override
  ConsumerState<UserListPage> createState() => _UserListPageState();
}

class _UserListPageState extends ConsumerState<UserListPage> {
  final _scrollController = ScrollController();
  final _searchController = TextEditingController();
  bool _isSearching = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _searchController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      final notifier = ref.read(userListProvider.notifier);
      if (notifier.hasMore) {
        notifier.loadMore();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final userListAsync = ref.watch(userListProvider);

    return Scaffold(
      appBar: AppBar(
        title: _isSearching
            ? TextField(
                controller: _searchController,
                decoration: InputDecoration(
                  hintText: '搜索用户...',
                  border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.white70),
                ),
                style: TextStyle(color: Colors.white, fontSize: 16),
                onChanged: (value) {
                  setState(() {});
                },
              )
            : Text('用户列表'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: Icon(_isSearching ? Icons.close : Icons.search),
            onPressed: () {
              setState(() {
                _isSearching = !_isSearching;
                if (!_isSearching) {
                  _searchController.clear();
                }
              });
            },
          ),
          if (!_isSearching)
            IconButton(
              icon: Icon(Icons.refresh),
              onPressed: () => ref.read(userListProvider.notifier).refresh(),
            ),
        ],
      ),
      body:
          _isSearching ? _buildSearchResults() : _buildUserList(userListAsync),
    );
  }

  Widget _buildSearchResults() {
    if (_searchController.text.isEmpty) {
      return Center(
        child: Text(
          '输入搜索关键词',
          style: TextStyle(fontSize: 16, color: Colors.grey),
        ),
      );
    }

    final searchAsync = ref.watch(userSearchProvider(_searchController.text));

    return searchAsync.when(
      data: (users) {
        if (users.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.search_off, size: 64, color: Colors.grey),
                SizedBox(height: 16),
                Text('未找到相关用户',
                    style: TextStyle(fontSize: 16, color: Colors.grey)),
              ],
            ),
          );
        }

        return ListView.builder(
          padding: EdgeInsets.all(8),
          itemCount: users.length,
          itemBuilder: (context, index) {
            return UserCard(user: users[index]);
          },
        );
      },
      loading: () => Center(child: CircularProgressIndicator()),
      error: (error, stack) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.red),
            SizedBox(height: 16),
            Text('搜索失败: $error',
                style: TextStyle(fontSize: 16, color: Colors.red)),
          ],
        ),
      ),
    );
  }

  Widget _buildUserList(AsyncValue<List<User>> userListAsync) {
    return userListAsync.when(
      data: (users) {
        if (users.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.people_outline, size: 64, color: Colors.grey),
                SizedBox(height: 16),
                Text('暂无用户数据',
                    style: TextStyle(fontSize: 16, color: Colors.grey)),
                SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () =>
                      ref.read(userListProvider.notifier).refresh(),
                  child: Text('重新加载'),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: () => ref.read(userListProvider.notifier).refresh(),
          child: ListView.builder(
            controller: _scrollController,
            padding: EdgeInsets.all(8),
            itemCount: users.length + 1,
            itemBuilder: (context, index) {
              if (index == users.length) {
                // 底部加载指示器
                final notifier = ref.read(userListProvider.notifier);
                if (notifier.hasMore) {
                  return Container(
                    padding: EdgeInsets.all(16),
                    alignment: Alignment.center,
                    child: CircularProgressIndicator(),
                  );
                } else {
                  return Container(
                    padding: EdgeInsets.all(16),
                    alignment: Alignment.center,
                    child: Text(
                      '没有更多数据了',
                      style: TextStyle(fontSize: 14, color: Colors.grey),
                    ),
                  );
                }
              }

              return UserCard(user: users[index]);
            },
          ),
        );
      },
      loading: () => Center(child: CircularProgressIndicator()),
      error: (error, stack) => Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.error_outline, size: 64, color: Colors.red),
            SizedBox(height: 16),
            Text(
              '加载失败: $error',
              style: TextStyle(fontSize: 16, color: Colors.red),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: () => ref.read(userListProvider.notifier).refresh(),
              child: Text('重试'),
            ),
          ],
        ),
      ),
    );
  }
}

class UserCard extends StatelessWidget {
  final User user;

  const UserCard({Key? key, required this.user}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: EdgeInsets.symmetric(vertical: 4),
      child: ListTile(
        leading: CircleAvatar(
          radius: 25,
          backgroundImage: NetworkImage(user.avatar),
          onBackgroundImageError: (_, __) {},
          child: Text(user.name[0]),
        ),
        title: Text(
          user.name,
          style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              user.email,
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
            SizedBox(height: 2),
            Text(
              user.company,
              style: TextStyle(fontSize: 12, color: Colors.blue),
            ),
          ],
        ),
        trailing: Icon(Icons.arrow_forward_ios, size: 16),
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => UserDetailPage(userId: user.id),
            ),
          );
        },
      ),
    );
  }
}

class UserDetailPage extends ConsumerWidget {
  final int userId;

  const UserDetailPage({Key? key, required this.userId}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userDetailAsync = ref.watch(userDetailsProvider(userId));

    return Scaffold(
      appBar: AppBar(
        title: Text('用户详情'),
        backgroundColor: Colors.blue,
        foregroundColor: Colors.white,
      ),
      body: userDetailAsync.when(
        data: (user) => Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(height: 32),
              CircleAvatar(
                radius: 60,
                backgroundImage: NetworkImage(user.avatar),
                onBackgroundImageError: (_, __) {},
                child: Text(user.name[0], style: TextStyle(fontSize: 32)),
              ),
              SizedBox(height: 24),
              Text(
                user.name,
                style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 8),
              Text(
                user.email,
                style: TextStyle(fontSize: 16, color: Colors.grey[600]),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 16),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Text(
                  user.company,
                  style: TextStyle(fontSize: 14, color: Colors.blue),
                ),
              ),
              SizedBox(height: 32),
              // 更多详情信息...
              Card(
                child: Padding(
                  padding: EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '个人信息',
                        style: TextStyle(
                            fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                      SizedBox(height: 12),
                      _buildInfoRow('用户ID', user.id.toString()),
                      _buildInfoRow('邮箱', user.email),
                      _buildInfoRow('公司', user.company),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        loading: () => Center(child: CircularProgressIndicator()),
        error: (error, stack) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.error_outline, size: 64, color: Colors.red),
              SizedBox(height: 16),
              Text(
                '加载失败: $error',
                style: TextStyle(fontSize: 16, color: Colors.red),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 16),
              ElevatedButton(
                onPressed: () {
                  ref.invalidate(userDetailsProvider(userId));
                },
                child: Text('重试'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: TextStyle(fontSize: 14, color: Colors.grey[600]),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: TextStyle(fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }
}
